package com.dwxt.stadium.service;

import com.dwxt.common.util.OkHttpUtils;

import com.dwxt.stadium.constant.OrderStatus;
import com.dwxt.stadium.entity.PayOrder;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class TaskService {
    private static List<String> statusList = new ArrayList<>();

    private static Map<Integer, String> map = new HashMap<>();

    static {
        statusList.add(OrderStatus.PLACE);
        statusList.add(OrderStatus.REQUEST_REFUND);

        map.put(5, OrderStatus.PLACE);
        map.put(2, OrderStatus.PAY);
        //动美 请求退款和取消支付都是 4
        map.put(4, OrderStatus.Fail);
        map.put(3, OrderStatus.REFUND);
        //拒绝退款，变成成功
        map.put(1, OrderStatus.PAY);
    }

    @Autowired
    private StadiumService stadiumService;

    @Value("${dongMei.url}")
    private String dongMeiUrl;

    public void checkOrder() {
        List<PayOrder> orderList = stadiumService.selectOrderByStatus(statusList);
        Map<String, String> headers = new HashMap<>();
        headers.put("username", "15123058497");
        headers.put("Signature", "2ddfeb530a2e81c9f45ed37398e6a20ec357d1c9");
        for (PayOrder order : orderList) {
            try {
                String url = dongMeiUrl + "order?OrderNumber=" + order.getOrderNumber();
                JSONObject result = JSONObject.fromObject(OkHttpUtils.synGet(url, headers));
                if (result.getInt("errorcode") == 0) {
                    //int statusCode = result.getJSONObject("value").getInt("StatusCode");
                    String statusMessage = result.getJSONObject("value").getString("StatusMessage");
                    //String status = map.get(statusCode);
                    order.setStatus(statusMessage);
                    //System.out.println(statusCode);
                    //修改订单状态
                    stadiumService.updateOrder(order);
                }
            } catch (Exception e) {
                log.error(e.toString());
            }
        }
    }
}
